﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Smart.UI.BaseClasses;
using Smart.MembershipService;

namespace Smart.Pages
{
    public partial class Profile : AuthenticatedPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                PopulateData();
            }
        }

        private void PopulateData()
        {
            User currentUser = Global.MembershipService.GetUserById(CurrentUserId);

            if (currentUser != null)
            {
                CurrentUser = currentUser;

                tbEmail.Text = currentUser.Email;
                tbFirstName.Text = currentUser.FirstName;
                tbLastName.Text = currentUser.LastName;
                tbPhone.Text = currentUser.Phone;
            }
        }

        protected void UpdateUserButton_Click(object sender, EventArgs e)
        {
            User currentUser = CurrentUser;

            if (currentUser != null)
            {
                currentUser.Email = tbEmail.Text;
                currentUser.FirstName = tbFirstName.Text;
                currentUser.LastName = tbLastName.Text;
                currentUser.Phone = tbPhone.Text;

                if (cboxChangePassword.Checked && tbPassword.Text != String.Empty)
                {
                    currentUser.Password = tbPassword.Text;
                    Global.MembershipService.RegisterUser(currentUser);
                }
                else
                {
                    Global.MembershipService.UpdateUser(currentUser);
                }

                Response.Redirect("~/Pages/Home.aspx");
            }
        }

        private User CurrentUser
        {
            get
            {
                if (ViewState["__currentUser"] != null)
                {
                    return ViewState["__currentUser"] as User;
                }
                return null;
            }
            set
            {
                ViewState["__currentUser"] = value;
            }
        }
    }
}